<template>
  <div class="pending-orders-container">
    <el-card class="header-card">
      <h2><el-icon><Clock /></el-icon> 待支付订单</h2>
    </el-card>

    <el-card v-loading="loading">
      <el-empty v-if="pendingOrders.length === 0 && !loading" description="暂无待支付订单" />

      <!-- 批量操作栏 -->
      <div v-if="pendingOrders.length > 0" class="batch-operations">
        <div class="batch-left">
          <el-checkbox 
            v-model="selectAll" 
            :indeterminate="isIndeterminate"
            @change="handleSelectAll"
          >
            全选
          </el-checkbox>
          <span class="selected-count">已选择 {{ selectedOrders.length }} 个订单</span>
        </div>
        <div class="batch-right">
          <el-button
            type="primary"
            :icon="Wallet"
            :disabled="selectedOrders.length === 0"
            @click="handleBatchPay"
            size="large"
          >
            批量支付 ({{ selectedOrders.length }})
          </el-button>
        </div>
      </div>

      <transition-group name="order-fade" tag="div" class="orders-list">
        <div class="order-item" v-for="order in pendingOrders" :key="order.orderId">
          <div class="order-header">
            <div class="order-info">
              <el-checkbox 
                v-model="order.selected" 
                @change="handleOrderSelect"
                class="order-checkbox"
              />
              <span class="order-no">订单号：{{ order.orderNo }}</span>
              <el-tag type="warning">待支付</el-tag>
            </div>
            <div class="order-actions">
              <el-button
                type="primary"
                size="small"
                :icon="Wallet"
                @click="handlePayOrder(order)"
              >
                立即支付
              </el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Close"
                @click="handleCancelOrder(order.orderId!)"
              >
                取消订单
              </el-button>
            </div>
          </div>

          <div class="order-body">
            <div class="delivery-info">
              <p><strong>联系人：</strong>{{ order.contactName }}</p>
              <p><strong>联系电话：</strong>{{ order.contactPhone }}</p>
              <p><strong>配送地址：</strong>{{ order.deliveryAddress }}</p>
              <p v-if="order.remark"><strong>备注：</strong>{{ order.remark }}</p>
            </div>
            <div class="order-meta">
              <p><strong>下单时间：</strong>{{ formatTime(order.createTime) }}</p>
              <p><strong>订单总额：</strong><span class="total-amount">¥{{ order.totalAmount }}</span></p>
            </div>
          </div>
        </div>
      </transition-group>
    </el-card>

    <!-- 支付对话框 -->
    <el-dialog
      v-model="showPaymentDialog"
      title="订单支付"
      width="500px"
      @close="resetPaymentForm"
    >
      <el-form :model="paymentForm" :rules="paymentRules" ref="paymentFormRef" label-width="100px">
        <el-form-item label="订单号">
          <el-input :model-value="currentOrder?.orderNo || ''" disabled />
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input :model-value="currentOrder?.totalAmount || ''" disabled>
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-radio-group v-model="paymentForm.paymentMethod">
            <el-radio label="微信支付">微信支付</el-radio>
            <el-radio label="支付宝">支付宝</el-radio>
            <el-radio label="现金支付">现金支付</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPaymentDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmPayment" :loading="paying">确认支付</el-button>
      </template>
    </el-dialog>

    <!-- 批量支付对话框 -->
    <el-dialog
      v-model="showBatchPaymentDialog"
      title="批量支付订单"
      width="600px"
      @close="resetBatchPaymentForm"
    >
      <div class="batch-payment-content">
        <div class="payment-summary">
          <h4>支付汇总</h4>
          <div class="summary-details">
            <div class="summary-item">
              <span>订单数量：</span>
              <span class="value">{{ selectedOrders.length }} 个</span>
            </div>
            <div class="summary-item">
              <span>总金额：</span>
              <span class="value total-amount">¥{{ batchTotalAmount.toFixed(2) }}</span>
            </div>
          </div>
        </div>
        
        <div class="selected-orders">
          <h4>选中订单</h4>
          <div class="order-list">
            <div v-for="order in selectedOrders" :key="order.orderId" class="order-summary">
              <span class="order-no">{{ order.orderNo }}</span>
              <span class="order-amount">¥{{ order.totalAmount }}</span>
            </div>
          </div>
        </div>
        
        <el-form :model="batchPaymentForm" :rules="batchPaymentRules" ref="batchPaymentFormRef" label-width="100px">
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-radio-group v-model="batchPaymentForm.paymentMethod">
              <el-radio label="微信支付">微信支付</el-radio>
              <el-radio label="支付宝">支付宝</el-radio>
              <el-radio label="现金支付">现金支付</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showBatchPaymentDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmBatchPayment" :loading="batchPaying">
          确认批量支付 (¥{{ batchTotalAmount.toFixed(2) }})
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { Clock, Wallet, Close } from '@element-plus/icons-vue';
import { getOrdersByUserId, payOrder, updateOrder, deleteOrder } from '@/api/order';
import { useUserStore } from '@/stores/user';
import type { Order } from '@/types';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';

const userStore = useUserStore();

const pendingOrders = ref<(Order & { selected?: boolean })[]>([]);
const loading = ref(false);
const showPaymentDialog = ref(false);
const paying = ref(false);
const paymentFormRef = ref<FormInstance>();
const currentOrder = ref<Order | null>(null);

// 批量支付相关
const showBatchPaymentDialog = ref(false);
const batchPaying = ref(false);
const batchPaymentFormRef = ref<FormInstance>();
const selectAll = ref(false);
const isIndeterminate = ref(false);

const paymentForm = reactive({
  paymentMethod: '微信支付'
});

const batchPaymentForm = reactive({
  paymentMethod: '微信支付'
});

const paymentRules: FormRules = {
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
};

const batchPaymentRules: FormRules = {
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
};

// 计算属性
const selectedOrders = computed(() => {
  return pendingOrders.value.filter(order => order.selected);
});

const batchTotalAmount = computed(() => {
  return selectedOrders.value.reduce((total, order) => total + order.totalAmount, 0);
});

// 加载待支付订单列表
const loadPendingOrders = async () => {
  if (!userStore.userId) return;
  
  loading.value = true;
  try {
    const response = await getOrdersByUserId(userStore.userId);
    if (response.operateResult === 'SUCC' && response.data) {
      // 只显示待支付的订单（orderStatus === '0'），并添加selected属性
      pendingOrders.value = response.data
        .filter(order => order.orderStatus === '0')
        .map(order => ({ ...order, selected: false }))
        .sort((a, b) => {
          return new Date(b.createTime || '').getTime() - new Date(a.createTime || '').getTime();
        });
    } else {
      pendingOrders.value = [];
    }
  } catch (error) {
    ElMessage.error('加载订单失败');
    pendingOrders.value = [];
  } finally {
    loading.value = false;
  }
};

// 格式化时间 - 显示完整日期时间
const formatTime = (time?: string) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

// 显示支付对话框
const handlePayOrder = (order: Order) => {
  currentOrder.value = order;
  paymentForm.paymentMethod = '微信支付';
  showPaymentDialog.value = true;
};

// 确认支付
const handleConfirmPayment = async () => {
  if (!paymentFormRef.value || !currentOrder.value) return;
  
  await paymentFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    paying.value = true;
    try {
      // 调用支付接口
      const response = await payOrder(currentOrder.value.orderId!, paymentForm.paymentMethod);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('支付成功！');
        showPaymentDialog.value = false;
        await loadPendingOrders();
      } else {
        ElMessage.error(response.errorMsg || '支付失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '支付失败');
    } finally {
      paying.value = false;
    }
  });
};

// 取消订单（实际删除订单）
const handleCancelOrder = (orderId: number) => {
  ElMessageBox.confirm('确定要取消该订单吗？取消后订单将被删除，无法恢复。', '提示', {
    confirmButtonText: '确定取消',
    cancelButtonText: '保留订单',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteOrder(orderId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('订单已取消并删除');
        await loadPendingOrders();
      } else {
        ElMessage.error(response.errorMsg || '取消失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '取消失败');
    }
  }).catch(() => {
    // 用户取消操作，不做任何处理
  });
};


// 重置支付表单
const resetPaymentForm = () => {
  paymentFormRef.value?.resetFields();
  currentOrder.value = null;
};

// 全选处理
const handleSelectAll = (checked: boolean) => {
  pendingOrders.value.forEach(order => {
    order.selected = checked;
  });
};

// 单个订单选择处理
const handleOrderSelect = () => {
  const selectedCount = selectedOrders.value.length;
  const totalCount = pendingOrders.value.length;
  
  selectAll.value = selectedCount === totalCount;
  isIndeterminate.value = selectedCount > 0 && selectedCount < totalCount;
};

// 批量支付
const handleBatchPay = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请选择要支付的订单');
    return;
  }
  batchPaymentForm.paymentMethod = '微信支付';
  showBatchPaymentDialog.value = true;
};

// 确认批量支付
const handleConfirmBatchPayment = async () => {
  if (!batchPaymentFormRef.value) return;
  
  await batchPaymentFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    batchPaying.value = true;
    try {
      const promises = selectedOrders.value.map(order => 
        payOrder(order.orderId!, batchPaymentForm.paymentMethod)
      );
      
      const results = await Promise.all(promises);
      
      // 检查所有支付是否成功
      const successCount = results.filter(result => result.operateResult === 'SUCC').length;
      const failCount = results.length - successCount;
      
      if (successCount === results.length) {
        ElMessage.success(`批量支付成功！共支付 ${successCount} 个订单`);
      } else if (successCount > 0) {
        ElMessage.warning(`部分支付成功！成功 ${successCount} 个，失败 ${failCount} 个`);
      } else {
        ElMessage.error('批量支付失败');
      }
      
      showBatchPaymentDialog.value = false;
      await loadPendingOrders();
    } catch (error: any) {
      ElMessage.error(error.message || '批量支付失败');
    } finally {
      batchPaying.value = false;
    }
  });
};

// 重置批量支付表单
const resetBatchPaymentForm = () => {
  batchPaymentFormRef.value?.resetFields();
  // 清空选择
  pendingOrders.value.forEach(order => {
    order.selected = false;
  });
  selectAll.value = false;
  isIndeterminate.value = false;
};

onMounted(() => {
  loadPendingOrders();
});
</script>

<style scoped>
.pending-orders-container {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-card h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.order-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.order-fade-enter-active,
.order-fade-leave-active {
  transition: all 0.3s ease;
}

.order-fade-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.order-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fdf6ec;
  border-bottom: 1px solid #ebeef5;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.order-no {
  font-weight: bold;
  color: #303133;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.order-body {
  padding: 20px;
  display: flex;
  justify-content: space-between;
}

.delivery-info {
  flex: 1;
}

.delivery-info p,
.order-meta p {
  margin: 8px 0;
  color: #606266;
}

.order-meta {
  text-align: right;
  min-width: 250px;
}

.total-amount {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}

/* 批量操作样式 */
.batch-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
  border-radius: 8px;
}

.batch-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.selected-count {
  color: #606266;
  font-size: 14px;
}

.batch-right {
  display: flex;
  align-items: center;
}

/* 订单复选框样式 */
.order-checkbox {
  margin-right: 10px;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 批量支付对话框样式 */
.batch-payment-content {
  max-height: 500px;
  overflow-y: auto;
}

.payment-summary {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.payment-summary h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.summary-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.summary-item .value {
  font-weight: bold;
  font-size: 18px;
  color: #303133;
}

.summary-item .value.total-amount {
  color: #f56c6c;
  font-size: 24px;
}

.selected-orders {
  margin-bottom: 20px;
}

.selected-orders h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.order-list {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 10px;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-summary:last-child {
  border-bottom: none;
}

.order-summary .order-no {
  font-family: monospace;
  color: #606266;
}

.order-summary .order-amount {
  font-weight: bold;
  color: #f56c6c;
}
</style>

